import React, { useEffect, useState } from "react";
import { Button, Space, Table, Tag } from "antd";
import type { TableProps } from "antd";
import instance from "../../api/request";
import type { FormProps } from "antd";
import { Checkbox, Form, Input, Modal } from "antd";
import { useNavigate } from "react-router-dom";
import useAuth from "../../hooks/useAuth";
function Index() {
    useAuth()
  interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
  }
  type FieldType = {
    tag?: string;
    content?: string;
    keyword?: string;
  };
  const [data, setData] = useState([]);
  const [total, setTotal] = useState();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [title, setTitle] = useState();
  const [tag, setTag] = useState();
  const [rest] = Form.useForm();
  const [addForm]=Form.useForm()
  const [flag,setFlag]=useState(false)
  const [id,setId]=useState()
  const getData = () => {
    const params = { page, pageSize };
    if (title) params.keyword = title;
    if (tag) params.tag = tag;
    instance.get("/article/list", { params }).then((res) => {
      if (res.data.rows) {
        setData(res.data.rows);
        setTotal(res.data.count);
      }
    });
  };
  useEffect(() => {
    getData();
  }, [page, pageSize, tag, title]);
  const pageChange = (fneyepage, fenyepageSize) => {
    setPage(fneyepage);
    setPageSize(fenyepageSize);
  };
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
    setTag(values.tag);
    setTitle(values.title);
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };
  const chong = () => {
    rest.resetFields();
    setTag("");
    setTitle("");
    getData();
  };
  const nav=useNavigate()
  const cha=(info)=>{
    nav('/detail',{state:{info}})
  }
  const [columns] = useState<TableProps<DataType>["columns"]>([
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "内容",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },
    {
      title: "Tags",
      key: "tags",
      dataIndex: "tags",
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? "geekblue" : "green";
            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={()=>cha(record)}>详情</Button>
          <Button onClick={()=>bian(record)}>编辑</Button>
        </Space>
      ),
    },
  ]);
  const addonFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log(values);
    
    if(flag){
        instance.post(`/article`,{
            
            ...values,

            tagList:["HTTP"],
            categoryList:["HTTP"],
            authorId:47529555,
        }).then(res=>{
            console.log(res);
            
            getData()
            setIsModalOpen(false)
        })
    }else{
        instance.put(`/article/${id}`,{
            ...values,
            tagList:["HTTP"],
            categoryList:["HTTP"]
        }).then(res=>{
            setIsModalOpen(false)
            getData()
        })
    }
  };

  const addonFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };
  const bian=(record)=>{
    setIsModalOpen(true)
    setFlag(false)
    addForm.setFieldsValue(record)
    setId(record.id)
  }
  const [isModalOpen, setIsModalOpen] = useState(false);
  const zeng = () => {
    setIsModalOpen(true);
    setFlag(true)
    addForm.resetFields()
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <div>
        <Button onClick={zeng}>新增</Button>
      <Modal
        title={flag?'新增数据':'编辑数据'}
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          form={addForm}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={addonFinish}
          onFinishFailed={addonFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType> label="标题" name="title">
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="标签" name="content">
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Form
        name="basic1"
        layout="inline"
        form={rest}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 900 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType> label="标题" name="title">
          <Input />
        </Form.Item>
        <Form.Item<FieldType> label="标签" name="tag">
          <Input />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
        <Button onClick={chong}>重置</Button>
      </Form>
      <Table<DataType>
        columns={columns}
        dataSource={data}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: pageChange,
        }}
      />
    </div>
  );
}

export default Index;
